package com.binarysearch;

/**
 * 最基础的二分查找
 * 《图解算法》1.2Java版
 */
public class BinarySearch {
    public static void main(String[] args) {
//        int[] arry = {-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10};
        int[] arry = {1,3,5,7,9};
        BinarySearch lin = new BinarySearch();
        Integer res = lin.binarySearch(arry,3);
        if (res == null){
            System.out.println("数组中不存在该元素");
        }else {
            System.out.println("数组中存在item这个元素，它在数组的索引为" + res);
        }

    }

    /**
     *
     * @param arry 数组
     * @param item 被猜的答案
     * @return
     */
    public Integer binarySearch(int[] arry, int item){

        int low = 0;
        int high = arry.length - 1;

        while (low <= high){
            int mid = (low + high) / 2;
            int guess = arry[mid];
            if (guess > item){
                high = mid - 1;
            }else if (guess < item){
                low = mid + 1;
            }else if (guess == item){
                return mid;
            }
        }
        return null;
    }

}
